package com.rc.saas.mini.minip.token;

import com.rc.saas.mini.component.RedisLoader;
import com.rc.saas.mini.component.UidGenerator;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis登录TOKEN管理器,支持自动重连
 */
@Component
public class RedisTokenLoader implements TokenLoader {
    private static Logger logger = LogManager.getLogger(RedisTokenLoader.class);

    //token有效期（720小时）:15天
    public static final int TOKEN_EXPIRES_HOUR = 360;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private RedisLoader redisLoader;

    @Override
    public String createToken(LoginInfoVo loginInfo) {
        String token = uidGenerator.genLoginToken();
        loginInfo.setToken(token);

        try {
            redisLoader.opsForValueSet(token, loginInfo, TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
            logger.info("成功创建TOKEN:{}", token);
            return token;
        } catch (Exception e) {
            logger.error("createToken 报错", e);
            return null;
        }
    }

    @Override
    public Boolean verifyToken(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }

        try {
            LoginInfoVo loginInfo = redisLoader.opsForValueGet(token, LoginInfoVo.class);
            if (loginInfo != null) {
                //如果验证成功，说明此用户进行了一次有效操作，更新过期时间
                redisLoader.opsForValueSet(token, loginInfo, TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
                logger.info("成功刷新TOKEN:{}", token);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            logger.error("verifyToken 报错", e);
            return null;
        }
    }

    @Override
    public LoginInfoVo readToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }

        try {
            LoginInfoVo loginInfo = redisLoader.opsForValueGet(token, LoginInfoVo.class);
            if (loginInfo != null) {
                redisLoader.opsForValueSet(token, loginInfo, TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
                logger.info("成功读取TOKEN:{}", token);

//                if (!tenantConfig.getTenantCode().equals(loginInfo.getTenantCode())) {
//                    logger.error("用户所属运营商非当前运营商 用户,{},当前,{}", loginInfo.getTenantCode(), tenantConfig.getTenantCode());
//                    return null;
//                }
                return loginInfo;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("readToken 报错", e);
            return null;
        }
    }

    @Override
    public String updateToken(String token, LoginInfoVo updateLoginInfo) {
        redisLoader.opsForValueSet(token, updateLoginInfo, TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return token;
    }

    @Override
    public void deleteToken(String token) {
        try {
            Boolean result = redisLoader.delete(token);
            if (result) {
                logger.info("成功删除TOKEN:{}", token);
            } else {
                logger.error("无法删除TOKEN:{}", token);
            }
        } catch (Exception e) {
            logger.error("verifyToken 报错", e);
        }
    }




}
